package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.TravelsQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyTagService;
import cn.wolfcode.luowowo.article.service.ITravlesService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annoation.LoginCheck;
import cn.wolfcode.luowowo.website.annoation.UserParam;
import cn.wolfcode.luowowo.website.web.util.UMEditorUploader;
import cn.wolfcoe.luowowo.common.util.baiducheck.SensitiveWordsUtil;
import cn.wolfcoe.luowowo.common.util.AjaxResult;
import cn.wolfcoe.luowowo.common.util.MyBeanUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private ITravlesService travlesService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisVOService travelStatisVOService;
    @Reference
    private IStrategyStatisVOService strategyStatisVOService;



    @Value("${file.path}")
    private String filePath;

    @RequestMapping("")
    public String travels(Model model, @ModelAttribute("qo") TravelsQuery qo) {
        //查询公开的,并且状态是已经发布的
        int[] arr = {2};
        qo.setState( arr );
        PageInfo pageInfo = travlesService.query( qo );
        List <Travel> list = pageInfo.getList();
        for (Travel t : list) {
            TravelStatisVO vo = travelStatisVOService.getTravelStatisVO( t.getId() );
            MyBeanUtil.copyProperties( t, vo );
        }
        pageInfo.setList( list );
        model.addAttribute( "pageInfo", pageInfo );
        List <TravelComment> tcs = travelCommentService.selectNewCommentTop10();
        model.addAttribute( "tcs", tcs );

        List <StrategyStatisVO> hotCds = strategyStatisVOService.queryHotStrategyTop10();
        model.addAttribute( "hotCds", hotCds.size()>5?hotCds.subList( 0,5 ):hotCds  );

        return "travel/list";
    }

    @LoginCheck
    @RequestMapping("/input")
    public String input(Model model, Long id, @UserParam UserInfo userInfo) {
        List <Destination> dests = destinationService.getDestsByDeep( 3 );
        model.addAttribute( "dests", dests );
        if (id != null) {
            Travel detail = travlesService.checkAndQueryTravel( id, userInfo );
            TravelContent content = travlesService.queryContent( id );
            detail.setTravelContent( content );
            model.addAttribute( "tv", detail );
        }

        return "travel/input";

    }

    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader( request );
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles( fileType );
        //  up.setMaxSize(10000); //单位KB
        up.upload( upfile, filePath );

        String callback = request.getParameter( "callback" );
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @LoginCheck
    public AjaxResult saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        travel.setAuthor( userInfo );
        Long id = travlesService.saveOrUpdate( travel, userInfo );
        return AjaxResult.SUCCESS.addData( id );
    }

    @RequestMapping("/detail")
    public String detail(Model model, Long id, @UserParam UserInfo userInfo) {
        Travel detail = travlesService.get( id );
        TravelContent content = travlesService.queryContent( id );
        detail.setTravelContent( content );
        model.addAttribute( "detail", detail );
        List <Destination> toasts = destinationService.getToasts( detail.getDest().getId() );
        Destination destination = toasts.remove( toasts.size() - 1 );
        model.addAttribute( "toasts", toasts );
        model.addAttribute( "dest", destination );
        //查存目的地下前3的攻略
        List <StrategyDetail> sds = strategyDetailService.selectViewNumTop3( detail.getDest().getId() );
        model.addAttribute( "sds", sds );
        //目的地下前三的游记
        List <Travel> ts = travlesService.selectViewNumTop3( detail.getDest().getId() );
        model.addAttribute( "ts", ts );
        //查询该游记下所有的评论
        TravelCommentQuery query = new TravelCommentQuery();
        query.setTravelId( id );
        query.setPageSize( Integer.MAX_VALUE );
        Page <TravelComment> page = travelCommentService.query( query );
        model.addAttribute( "list", page.getContent() );
        //阅读数+1
        travelStatisVOService.viewnumIncrease( id, 1 );
        if (userInfo != null) {
            Boolean isFavor = travelStatisVOService.checkFavor( id, userInfo.getId() );
            model.addAttribute( "isFavor", isFavor );
        }
        //查询游记的前10条
        model.addAttribute( "vo", travelStatisVOService.getTravelStatisVO( id ) );
        return "travel/detail";
    }

    @RequestMapping("/commentAdd")
    @LoginCheck
    public String saveOrUpdate(Model model, TravelComment comment, @UserParam UserInfo userInfo) {

        comment.setUserId( userInfo.getId() );
        comment.setCity( userInfo.getCity() );
        comment.setHeadUrl( userInfo.getHeadImgUrl() );
        comment.setLevel( userInfo.getLevel() );
        comment.setUsername( userInfo.getNickname() );
        comment.setContent( SensitiveWordsUtil.SensitiveWordCheck( comment.getContent() ).getContent() );
        comment = travelCommentService.saveOrUpdate( comment );
        model.addAttribute( "c", comment );
        //返回当前foolr


        long floor = travelCommentService.getCount( comment.getTravelId() );
        model.addAttribute( "floor", floor );
        return "travel/commentTpl";
    }

    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Model model, Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult( false, "请先登录" );
            result.setCode( 102 );
            return result;
        }
        Boolean flag = travelStatisVOService.favor( tid, userInfo );
        String zetKey = RedisKeys.STRATEGY_STATIS_ZSET_COMMEND.getPrifx();
        //如果返回值为null,那么往用户收藏list中添加一条数据




        return new AjaxResult( flag ).addData( travelStatisVOService.getTravelStatisVO( tid ) );
    }

    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object strategyThumbup(Model model, Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult( false, "请先登录" );
            result.setCode( 102 );
            return result;
        }
        Boolean flag = travelStatisVOService.travelThumbup( tid, userInfo.getId() );
        return new AjaxResult( flag ).addData( travelStatisVOService.getTravelStatisVO( tid ) );
    }
    //转发接口
    @RequestMapping("/travelShare")
    @ResponseBody
    public Object travelShare(Model model, Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult result = new AjaxResult( false, "请先登录" );
            result.setCode( 102 );
            return result;
        }
        Boolean flag = travelStatisVOService.travelShare( tid, userInfo.getId() );
        return new AjaxResult( flag ).addData( travelStatisVOService.getTravelStatisVO( tid ) );
    }

}
